using System.Reflection;
using System.Runtime.Loader;
using Autofac;
using Crossborder.Core.Core;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyModel;

namespace Crossborder.Extensions
{
    public class AutofacExtension : Autofac.Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            var libs = DependencyContext.Default.CompileLibraries.Where(x => !x.Serviceable && x.Type == "project").ToList();
            List<Assembly> assemblies = new();
            foreach (var lib in libs)
            {
                assemblies.Add(AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(lib.Name)));
            }

            builder.RegisterAssemblyTypes(assemblies.ToArray()).Where(t => t.IsAssignableTo<ControllerBase>() && !t.IsAbstract && !t.IsInterface).AsSelf().PropertiesAutowired();
            
            // 瞬态
            builder.RegisterAssemblyTypes(assemblies.ToArray()).Where(t => t.IsAssignableTo<ITransient>() && !t.IsAbstract && !t.IsInterface).AsSelf().AsImplementedInterfaces().PropertiesAutowired();

            // 单例 
            builder.RegisterAssemblyTypes(assemblies.ToArray()).Where(t => t.IsAssignableTo<ISingleton>() && !t.IsAbstract && !t.IsInterface).AsSelf().AsImplementedInterfaces().SingleInstance().PropertiesAutowired(); 

            // 作用域
            builder.RegisterAssemblyTypes(assemblies.ToArray()).Where(t => t.IsAssignableTo<IScoped>() && !t.IsAbstract && !t.IsInterface).AsSelf().AsImplementedInterfaces().InstancePerLifetimeScope().PropertiesAutowired();
        }
    }
}